package edu.pod.hoteishilton.persistence;

import edu.pod.hoteishilton.exception.DuplicatedEntityException;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

public class FileObjectContainer {

    private static Configuration configuration;
    //escrita
    protected FileOutputStream fileOutputStream;
    protected ObjectOutputStream objectOutputStream;
    //leitura
    protected FileInputStream fileInputStream;
    protected ObjectInputStream objectInputStream;
    protected FileReader reader;
    protected BufferedReader bufferedReader;
    private static File database;
    private static String databaseName;
    private HashMap objectsMapDatabase;

    public FileObjectContainer(Configuration configuration) {
        FileObjectContainer.configuration = configuration;
        databaseName = configuration.getDatabasePath() + configuration.getDatabaseName() + "." + configuration.getDatabaseExtension();
        System.out.println(databaseName);
        if (!databasePathExists()) {
            if (databasePathCreate()) {
                System.out.println("Diretório do banco criado.");
            } else {
                System.out.println("Diretório do banco não criado.");
            }
        } else {
            System.out.println("Diretório do banco já existe.");
        }

        try {
            databaseCreate();
        } catch (Exception ex) {
            Logger.getLogger(FileObjectContainer.class.getName()).log(Level.SEVERE, null, ex);
        }


    }

    public static Configuration newConfiguration() {
        return new Configuration();
    }

    public static boolean databasePathExists() {
        if (new File(configuration.getDatabasePath()).exists()) {
            return true;
        }
        return false;
    }

    public static boolean databasePathCreate() {
        File dir = new File(configuration.getDatabasePath());
        return dir.mkdir();
    }

    public static boolean databaseExists() {
        if (new File(configuration.getDatabasePath() + configuration.getDatabaseName() + "." + configuration.getDatabaseExtension()).exists()) {
            return true;
        }
        return false;
    }

    public void databaseCreate() throws Exception {
        if (databaseExists()) {
            database = new File(databaseName);
            fileInputStream = new FileInputStream(database);
            objectInputStream = new ObjectInputStream(fileInputStream);
            objectsMapDatabase = (HashMap) objectInputStream.readObject();
            System.out.println("Banco carregado.");
            objectInputStream.close();
            fileInputStream.close();
        } else {
            try {
                database = new File(databaseName);
                //database = new File(configuration.getDatabaseName() + "." + configuration.getDatabaseExtension()).getAbsoluteFile();
                fileOutputStream = new FileOutputStream(configuration.getDatabaseName() + "." + configuration.getDatabaseExtension());
                objectOutputStream = new ObjectOutputStream(fileOutputStream);
                objectsMapDatabase = new HashMap();
                objectOutputStream.writeObject(objectsMapDatabase);
                System.out.println("Banco criado.");
                objectOutputStream.close();
                fileOutputStream.close();
            } catch (FileNotFoundException e) {
                System.out.println("Erro: " + e.getMessage());
            }
        }
    }

    /**
     * Fecha o ObjectContainer
     *
     * @return true denota que a ultima instancia do conteiner e dos arquivos de
     * DB foram fechados
     * @throws FileIOException
     */
    public boolean close() throws FileIOException {
        try {
            objectInputStream.close();
            objectInputStream.close();
            objectOutputStream.close();
            fileOutputStream.close();
            database = null;
            objectsMapDatabase = null;
            return true;
        } catch (IOException ex) {
            return false;
        }
    }

    public HashMap<String, HashMap<String, Object>> getDatabase() {
        try {
//            if(objectsMapDatabase == null){
//                objectsMapDatabase = new HashMap();
//            }
            return objectsMapDatabase;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public boolean refresh() {
        try {
            fileOutputStream = new FileOutputStream(database);
            FileOutputStream file = new FileOutputStream(database);
            objectOutputStream = new ObjectOutputStream(fileOutputStream);
            objectOutputStream.writeObject(objectsMapDatabase);
            objectOutputStream.close();
            file.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public boolean load() {
        return false;
    }

    public void commit() throws Exception {
        try {
            objectOutputStream.writeObject(database);
        } catch (Exception e) {
        }
    }

    public void createEntity(String name) throws DuplicatedEntityException {
    }

    public void delete(Object obj) {
    }

    public static void store(Object obj) {
        System.out.println(obj.getClass().getSimpleName());
    }

    public List<HashMap<String, Integer>> getList(HashMap<String, Integer> contadores) {
        System.out.println("O getList Ainda nao esta Implementado!");
        return null;
    }
}